package cn.tedu.egweibo05.controller;

import cn.tedu.egweibo05.base.response.JsonResult;
import cn.tedu.egweibo05.base.response.StatusCode;
import cn.tedu.egweibo05.mapper.UserMapper;
import cn.tedu.egweibo05.pojo.dto.UserDTO;
import cn.tedu.egweibo05.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo05.pojo.entity.User;
import cn.tedu.egweibo05.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users")
@Api(tags = "用户管理模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/reg")
    @ApiOperation("注册")
    @ApiImplicitParam(name = "userDTO", value = "用户注册信息", required = true, dataType = "UserDTO")
    public JsonResult reg(@Validated @RequestBody UserDTO userDTO) {
        UserVO userVO = userMapper.selectByUsername(userDTO.getUsername());
        if (userVO != null) return new JsonResult(StatusCode.USERNAME_ALREADY_EXISTS);
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return JsonResult.ok();
    }

    @PostMapping("/login")
    @ApiOperation("登录")
    @ApiImplicitParam(name = "userLoginDTO", value = "用户登录信息", required = true, dataType = "UserLoginDTO")
    public JsonResult login(@Validated @RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session) {
        UserVO userVO = userMapper.selectByUsername(userLoginDTO.getUsername());
        if (userVO == null) return new JsonResult(StatusCode.USERNAME_ERROR);
        if (!userVO.getPassword().equals(userLoginDTO.getPassword())) return new JsonResult(StatusCode.PASSWORD_ERROR);
        session.setAttribute("user", userVO);
        return JsonResult.ok();
    }

    @GetMapping("/currentUser")
    @ApiOperation("获取当前用户信息")
    public JsonResult currentUser(@ApiIgnore HttpSession session) {
        UserVO userVO = (UserVO) session.getAttribute("user");
        return JsonResult.ok(userVO);
    }

    @GetMapping("/logout")
    @ApiOperation("退出登录")
    public void logout(@ApiIgnore HttpSession session) {
        session.removeAttribute("user");
    }

}
